package thread;

import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author verlet
 * @date 2021-03-29 22:46
 */
public class ReentrantLockDemo {
    private static ReentrantLock lockA = new ReentrantLock();
    private static ReentrantLock lockB = new ReentrantLock();

    public static void main(String[] args) {
        Thread threadA = new Thread(()->{
            try {
                lockA.lockInterruptibly();

                System.out.println(Thread.currentThread()+"获取lockA,等待LockB");
                Thread.sleep(new Random().nextInt(500));

                lockB.lockInterruptibly();
                System.out.println(Thread.currentThread()+"获取LockB");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                if(lockA.isHeldByCurrentThread()){
                    System.out.println(Thread.currentThread()+"释放A锁");
                    lockA.unlock();
                }
                if(lockB.isHeldByCurrentThread()){
                    System.out.println(Thread.currentThread()+"释放B锁");
                    lockB.unlock();
                }
            }
        },"threadA" );

        Thread threadB= new Thread(()->{
            try {
                lockB.lockInterruptibly();

                System.out.println(Thread.currentThread()+"获取lockB,等待LockA");
                Thread.sleep(new Random().nextInt(500));

                lockA.lockInterruptibly();
                System.out.println(Thread.currentThread()+"获取LockA");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                if(lockA.isHeldByCurrentThread()){
                    System.out.println(Thread.currentThread()+"释放A锁");
                    lockA.unlock();
                }
                if(lockB.isHeldByCurrentThread()){
                    System.out.println(Thread.currentThread()+"释放B锁");
                    lockB.unlock();
                }
            }
        },"threadB" );

        threadA.start();
        threadB.start();

        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread()+"执行中断");
        threadA.interrupt();

    }

}
